﻿using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Threading;

namespace BillHelper
{
    public class NamedPipeServerStreamTool
    {
        private Thread tWaitForConnection;
        private const string PipeName = "SaoMiaoShiBie";

        private const int PipeInBufferSize = 4096;

        private const int PipeOutBufferSize = 65535;

        private static Encoding encoding = Encoding.UTF8;

        Action<string> actShow;


        public NamedPipeServerStreamTool(Action<string> actShow)
        {
            this.actShow = actShow;
            Console.WriteLine("开启服务");
            tWaitForConnection = new Thread(WhileWaitForConnection);
            tWaitForConnection.Start();
        }

        private void WhileWaitForConnection()
        {
            Console.WriteLine("服务已开启");
            while (true)
            {
                WaitForConnection();
                Thread.Sleep(500);
            }

        }
        private void WaitForConnection()
        {
            try
            {
                using (var _pipe = new NamedPipeServerStream
                (
                       PipeName,
                       PipeDirection.InOut,
                       1,
                       PipeTransmissionMode.Message,
                       PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                       PipeInBufferSize,
                       PipeOutBufferSize
                    )
                )
                {
                    _pipe.WaitForConnection();

                    var data = new byte[PipeInBufferSize];
                    var count = _pipe.Read(data, 0, PipeInBufferSize);
                    _pipe.WriteByte(0);
                    if (count > 0)
                    {
                        // 通信双方可以约定好传输内容的形式，例子中我们传输简单文本信息。
                        string message = encoding.GetString(data, 0, count);

                       // Console.WriteLine("收到消息 " + message);

                        actShow(message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("连接异常 " + ex.Message);
            }
        }
        //private void OnSend(object sender, RoutedEventArgs e)
        //{
        //    if (_pipe.IsConnected)
        //    {
        //        try
        //        {
        //            string message = txtSendMsg.Text;

        //            byte[] data = encoding.GetBytes(message);

        //            _pipe.Write(data, 0, data.Length);
        //            _pipe.Flush();
        //            _pipe.WaitForPipeDrain();
        //        }
        //        catch { }
        //    }

        //    Close();
        //}
    }
}
